package cn.gailvlun.gll.presentation.hotel.day

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.view.View
import cn.gailvlun.gll.R
import cn.gailvlun.gll.databinding.ActivityHotelWriteBinding
import cn.gailvlun.gll.mgr.UploadMgr
import cn.gailvlun.gll.mgr.UploadResult
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.hotel.AddInsomniaReq
import cn.gailvlun.gll.net.hotel.InsomniaCategory
import cn.gailvlun.gll.net.hotel.InsomniaHotel
import cn.gailvlun.gll.net.hotel.InsomniaType
import cn.gailvlun.gll.presentation.base.App
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.hotel.drawer.HotelMyShareActivity
import cn.gailvlun.gll.util.AudioUtil
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.ToastUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.FileUtils
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.Observables
import java.io.File


class HotelWriteActivity : BaseActivity() {

    companion object {
        fun openActivity(context: Context, localAudioFile: File? = null,
                         insomniaCategory: InsomniaCategory? = null) {
            val intent = Intent(context, HotelWriteActivity::class.java)
            intent.putExtra("localAudioFile", localAudioFile)
            intent.putExtra("insomniaCategory", insomniaCategory)
            context.startActivity(intent)
        }
    }

    private lateinit var mBinding: ActivityHotelWriteBinding

    private lateinit var pd: Dialog

    override fun initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_hotel_write)
        mBinding.nbv.setOnMenuClickListener {
            pd = DialogUtil.showIndeterminate(mContext)

            val insomniaReq = AddInsomniaReq()
            insomniaReq.title = mBinding.etTitle.text.toString()
            insomniaReq.text = mBinding.etContent.text.toString()
            
            insomniaReq.category = if (false)
                InsomniaCategory.T
            else
                InsomniaCategory.S

            if (mBinding.audioFile == null) {
                insomniaReq.type = InsomniaType.T
                sendToServer(insomniaReq)
            } else {
                insomniaReq.type = InsomniaType.V
                
                
                UploadMgr.getInstance().upload(FileUtils.getFileName(mBinding.audioFile), mBinding.audioFile?.path)
                        .compose(RxUtil.applySingleScheduler())
                        .compose(bindToLifecycle())
                        .subscribe(object : SingleObserver<UploadResult<PutObjectRequest, PutObjectResult>> {
                            override fun onSubscribe(d: Disposable) {

                            }

                            override fun onSuccess(t: UploadResult<PutObjectRequest, PutObjectResult>) {
                                insomniaReq.audio = t.request.objectKey
                                insomniaReq.audio_length = (AudioUtil.getDuration(mBinding.audioFile?.path) / 1000).toInt()
                                sendToServer(insomniaReq)
                            }

                            override fun onError(e: Throwable) {
                                DialogUtil.showError(mContext, getString(R.string.hotel_edit_record_upload_failure))
                                pd.dismiss()
                            }
                        })
            }
        }
        mBinding.nbv.setOnBackListener {
            onBackPressed()
        }

        val titleOb = RxTextView.textChanges(mBinding.etTitle)
        val contentOb = RxTextView.textChanges(mBinding.etContent)

        Observables.combineLatest(titleOb, contentOb) { c1, c2 ->
            c1.isNotEmpty() && c2.isNotEmpty()
        }.subscribe { isEnable ->
            mBinding.nbv.setMenuEnable(isEnable)
        }
    }

    fun sendToServer(req: AddInsomniaReq) {
        HttpMethods.getHotelService()
                .addInsomnia(req)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<InsomniaHotel>() {
                    override fun onSuccess(response: InsomniaHotel?) {
                        ToastUtil.showShort(getString(R.string.hotel_edit_record_upload_success))
                        finish()
                        ActivityUtils.finishActivity(HotelSpeakActivity::class.java)
                        HotelMyShareActivity.openActivity(mContext, req.type == InsomniaType.T)
                    }

                    override fun onFailure(errMsg: String?, response: InsomniaHotel?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        pd.dismiss()
                    }
                })
    }

    override fun createHandler() {

    }

    override fun onBackPressed() {
        MaterialDialog.Builder(mContext)
                .title(getString(R.string.hotel_edit_record_dialog_title))
                .positiveText(getString(R.string.ok))
                .onPositive { dialog, which ->
                    dialog.dismiss()
                    finish()
                }
                .negativeText(getString(R.string.cancel))
                .show()
    }

    override fun loadData(savedInstanceState: Bundle?) {
        val localAudioFile = intent.getSerializableExtra("localAudioFile") as File?
        mBinding.audioFile = localAudioFile

        val insomniaCategory = intent.getSerializableExtra("insomniaCategory") as InsomniaCategory?
        if (insomniaCategory == null) {
            
            mBinding.rgType.check(R.id.rb_type_fragment)
        } else {
            if (insomniaCategory == InsomniaCategory.T) {
                
                mBinding.rbTypeStory.visibility = View.GONE
                mBinding.rgType.check(R.id.rb_type_fragment)
            } else {
                
                mBinding.rbTypeFragment.visibility = View.GONE
                mBinding.rgType.check(R.id.rb_type_story)
            }
        }
    }

    override fun onDestroy() {
        mBinding.cpv.onDestroy()
        super.onDestroy()
    }

    object Util {
        @JvmStatic
        fun getTitleName(file: File?): String {
            val resource = App.getInstance().resources
            return if (file == null) resource.getString(R.string.hotel_day_write) else resource.getString(R.string.hotel_edit_record_title)

        }
    }

}